import React, { useState, useEffect } from 'react';
import { Button, Input, Card, message, Spin } from 'antd';
import axios from 'axios';

const { TextArea } = Input;

interface Message {
  role: 'user' | 'assistant';
  content: string;
  timestamp: number;
}

const AIChat: React.FC = () => {
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [loading, setLoading] = useState(false);
  const [autoGenerate, setAutoGenerate] = useState(false);

  // 百度智能云API配置
  const API_URL = "https://qianfan.baidubce.com/v2/chat/completions";
  const API_KEY = "bce-v3/ALTAK-K3cQIcUntkJ5niY0Fbm1c/02fbe8f7cc076f8610df688a9ced502c147a59ea";

  // 自动生成内容的函数
  const generateContent = async (prompt: string) => {
    try {
      setLoading(true);
      
      const response = await axios.post(API_URL, {
        model: "ernie-x1.1-preview",
        messages: [
          {
            role: "user",
            content: prompt
          }
        ]
      }, {
        headers: {
          Authorization: `Bearer ${API_KEY}`
        }
      });

      console.log('AI Response:', response.data);
      
      if (response.data.choices && response.data.choices[0]) {
        const aiResponse = response.data.choices[0].message.content;
        
        // 添加AI回复到消息列表
        const newMessage: Message = {
          role: 'assistant',
          content: aiResponse,
          timestamp: Date.now()
        };
        
        setMessages(prev => [...prev, newMessage]);
        message.success('内容生成成功！');
      } else {
        message.error('AI响应格式异常');
      }
    } catch (error) {
      console.error('AI生成失败:', error);
      message.error('AI生成失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 发送消息
  const sendMessage = async () => {
    if (!inputValue.trim()) return;

    const userMessage: Message = {
      role: 'user',
      content: inputValue,
      timestamp: Date.now()
    };

    setMessages(prev => [...prev, userMessage]);
    setInputValue('');
    
    // 调用AI生成回复
    await generateContent(inputValue);
  };

  // 自动生成预设内容
  const autoGenerateContent = async () => {
    const prompts = [
      "你好，我是小明，请帮我写一篇关于人工智能的文章",
      "请帮我写一首关于春天的诗",
      "请帮我写一个简单的JavaScript函数",
      "请帮我解释一下什么是机器学习",
      "请帮我写一个关于环保的演讲稿"
    ];

    const randomPrompt = prompts[Math.floor(Math.random() * prompts.length)];
    await generateContent(randomPrompt);
  };

  // 自动生成模式
  useEffect(() => {
    if (autoGenerate) {
      const interval = setInterval(() => {
        autoGenerateContent();
      }, 10000); // 每10秒自动生成一次

      return () => clearInterval(interval);
    }
  }, [autoGenerate]);

  return (
    <div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
      <Card title="🤖 百度智能云AI对话" style={{ marginBottom: '20px' }}>
        <div style={{ marginBottom: '20px' }}>
          <Button 
            type={autoGenerate ? 'primary' : 'default'}
            onClick={() => setAutoGenerate(!autoGenerate)}
            style={{ marginRight: '10px' }}
          >
            {autoGenerate ? '停止自动生成' : '开始自动生成'}
          </Button>
          <Button onClick={autoGenerateContent} disabled={loading}>
            随机生成内容
          </Button>
        </div>

        <div style={{ marginBottom: '20px' }}>
          <TextArea
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            placeholder="输入你的问题或需求..."
            rows={3}
            style={{ marginBottom: '10px' }}
          />
          <Button 
            type="primary" 
            onClick={sendMessage} 
            disabled={loading || !inputValue.trim()}
            style={{ width: '100%' }}
          >
            {loading ? <Spin size="small" /> : '发送'}
          </Button>
        </div>
      </Card>

      <Card title="💬 对话记录">
        <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
          {messages.length === 0 ? (
            <div style={{ textAlign: 'center', color: '#999', padding: '20px' }}>
              还没有对话记录，开始你的第一次对话吧！
            </div>
          ) : (
            messages.map((msg, index) => (
              <div
                key={index}
                style={{
                  marginBottom: '15px',
                  padding: '10px',
                  borderRadius: '8px',
                  backgroundColor: msg.role === 'user' ? '#e6f7ff' : '#f6ffed',
                  border: `1px solid ${msg.role === 'user' ? '#91d5ff' : '#b7eb8f'}`
                }}
              >
                <div style={{ 
                  fontWeight: 'bold', 
                  marginBottom: '5px',
                  color: msg.role === 'user' ? '#1890ff' : '#52c41a'
                }}>
                  {msg.role === 'user' ? '👤 用户' : '🤖 AI助手'}
                </div>
                <div style={{ whiteSpace: 'pre-wrap' }}>
                  {msg.content}
                </div>
                <div style={{ 
                  fontSize: '12px', 
                  color: '#999', 
                  marginTop: '5px',
                  textAlign: 'right'
                }}>
                  {new Date(msg.timestamp).toLocaleTimeString()}
                </div>
              </div>
            ))
          )}
        </div>
      </Card>
    </div>
  );
};

export default AIChat;

